package com.supreme.nettyapp.generalserver.beatserver.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import java.net.SocketAddress;

@ChannelHandler.Sharable
public class BeatServerHandler extends ChannelInboundHandlerAdapter {

    private int LossConnectTime = 0;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            String type = "";
            switch (event.state()) {
                case READER_IDLE:
                    type = "read idle";
                    break;

                case WRITER_IDLE:
                    type = "write idle";
                    break;

                case ALL_IDLE:
                    type = "all idle";
                    break;
            }

            System.out.println(ctx.channel().remoteAddress() + " 触发超时类型: " + type);
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String threadName = Thread.currentThread().getName();
        System.out.printf("%s %s 客户端上线\n", socketAddress, threadName);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String threadName = Thread.currentThread().getName();
        System.out.printf("%s %s 客户端下线\n", socketAddress, threadName);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        SocketAddress socketAddress = ctx.channel().remoteAddress();
        String threadName = Thread.currentThread().getName();
        System.out.printf("%s %s 获取客户端消息: %s\n", socketAddress, threadName, msg.toString());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
